package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Grid;

public class GridConfigManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public GridConfigManage(DBConn db)
	{
		this.db=db;
	}
	public GridConfigManage(DBPool dbpool)
	{
		this.dbpool=dbpool;
	}
	
	public Grid getData(int GridID)
	{
		Grid grid = new Grid();
		String sql="select * from Grid_Config where GridID="+GridID;
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			if(rs.next())
			{
				grid.setName(rs.getString("gridName"));
				grid.setAuthority(rs.getString("Authority"));
				grid.setLocalTime(rs.getString("Local_Time"));
				grid.setGridDesc(rs.getString("gridDesc"));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
		return grid;
	}

	public String addRecord(int GridID,Grid grid)
	{
		String gridName=grid.getName();
		String authority=grid.getAuthority();
		String localTime=grid.getLocalTime();
		String gridDesc=grid.getGridDesc();
		
		String sql="insert into Grid_Config (GridID,GridName,Authority,Local_Time,GridDesc) values ("+GridID+",'"+gridName+"','"+authority+"','"+localTime+"','"+gridDesc+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(int GridID)
	{
		String sql="delete from Grid_Config where GridID="+GridID ;
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String GridName)
	{
		String sql="delete from Grid_Config where GridName='"+GridName+"'";
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
